package com.ming_za.od_updater.core.updater;

import com.ming_za.od_updater.ODModConfig;
import com.ming_za.od_updater.core.updater.handler.ModTransmitHandle;
import com.ming_za.od_updater.core.updater.handler.ModUpdateHandle;
import com.ming_za.od_updater.core.window.LoadingState;
import com.ming_za.od_updater.core.window.page.FailPage;
import com.ming_za.od_updater.core.window.PageManager;
import com.ming_za.od_updater_sdk.ODUpdater;

public class UpdaterManager {

    private static ODUpdater updater = null;

    public static void startUpdate(){

        if (updater != null) {
            try {
                updater.awaitUpdateDone();
            } catch (InterruptedException ignored) {
            }
        }

        updater = ODUpdater.createUpdater(ODModConfig.serverIp,Long.parseLong(ODModConfig.resLabel), ODModConfig.unpublishKey, ODModConfig.rootDir);
        updater.setUpdateHandler(new ModUpdateHandle());
        updater.setIStreamTransmit(new ModTransmitHandle());
        updater.setLogger(new UpdaterLog());

        updater.getLogger().setEnabled(ODModConfig.debug);
        updater.getLogger().setDebug(ODModConfig.debug);

        try {
            if (!updater.startUpdate()){
                StateBridge.setLoadingState(LoadingState.CONTINUE);
            }
        }catch (Exception e){
            StateBridge.setUpdateState(UpdateState.UN_CONNECT);
            PageManager.setPage(new FailPage());
        }

    }

    public static void stopUpdate(){
        updater.shutdown();
    }

    public static void awaitUpdateDone() throws InterruptedException {
        updater.awaitUpdateDone();
    }

}
